﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using BizzCore;
using log4net;

namespace BizzUI.UserControls
{
    public partial class GlobalConfigurations : UserControl
    {
        const string par1 = "InboxProviders";
        const string val1 = "Ruta completa a las librerias de los tipos de bandeja de entrada";
        const string par2 = "OutboxProviders";
        const string val2 = "Ruta completa a las librerias de los tipos de bandeja de salida";
        const string par3 = "refreshInterval";
        const string val3 = "Tiempo (en segundos) de espera en la nueva búsqueda de mensajes sin leer.";
        const string par4 = "CustomReports";
        const string val4 = "Ruta completa a las librerias de los reportes desarrollados por terceros.";
        

        private static readonly ILog auditLog =
                    LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private DataTable bizSettings;
        private BindingSource bindingDataTable = new BindingSource();
        public GlobalConfigurations()
        {
            InitializeComponent();
            initDataTable();
            initDataGrid();
        }

        private void initDataGrid()
        {


            dgSettings.RowHeadersVisible = false;
          
            dgSettings.DataSource = bindingDataTable;
            dgSettings.Columns[0].ReadOnly = true;
            dgSettings.Columns[2].ReadOnly = true;
                    


            dgSettings.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dgSettings.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dgSettings.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            



        }

        private void initDataTable()
        {
            bizSettings = new DataTable("Settings");
            bizSettings.Columns.Add("Parámetro");
            bizSettings.Columns.Add("Valor");
            bizSettings.Columns.Add("Descripción");

           


            string[] inboxDllsConfig = new string[] { par1, ConfigurationManager.AppSettings[par1].ToString(), val1 };
            string[] outboxDllsConfig = new string[] { par2, ConfigurationManager.AppSettings[par2].ToString(), val2 };
            string[] processFrencuencyConfig = new string[] { par3, ConfigurationManager.AppSettings[par3].ToString(), val3 };
            string[] reportsDllsConfig = new string[] { par4, ConfigurationManager.AppSettings[par4].ToString(), val4 };

            bizSettings.Rows.Add(inboxDllsConfig);
            bizSettings.Rows.Add(outboxDllsConfig);
            bizSettings.Rows.Add(processFrencuencyConfig);
            bizSettings.Rows.Add(reportsDllsConfig);
            bindingDataTable.DataSource = bizSettings;
            
            
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            string oldRefreshInterval = ConfigurationManager.AppSettings[par3].ToString();
            try
            {
                string log = "";
                Configuration settings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                foreach (DataRow r in bizSettings.Rows)
                {
                    settings.AppSettings.Settings[r[0].ToString()].Value = r[1].ToString();
                    log+=r[0].ToString() + "="+ r[1].ToString() + " | ";

                }

                settings.Save();
                ConfigurationManager.RefreshSection("appSettings");
                BizzSystem s = BizzSystem.getInstance();
                s.setRefreshInterval(Int32.Parse(ConfigurationManager.AppSettings[par3].ToString()));
               
                MessageBox.Show(null, "Parámetros guardados correctamente. Si modificó las rutas a las librerías de tipo de bandeja, debe reiniciar la aplicación.","Cambios guardados", MessageBoxButtons.OK, MessageBoxIcon.Information);
                auditLog.Info("Cambio de configuración: " +log);
            }
            catch (Exception ex)
            {
                MessageBox.Show(null,"Ha ocurrido un error. Al menos uno de los parámetros ingresados no es válido. Por favor verifique",null,MessageBoxButtons.OK,MessageBoxIcon.Error);
                auditLog.Error(ex.Message);
                Configuration settings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                settings.AppSettings.Settings[par3].Value = oldRefreshInterval;
                settings.Save();
                ConfigurationManager.RefreshSection("appSettings");
            }
        }

        private void dgSettings_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgSettings.IsCurrentCellDirty)
            {
                dgSettings.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

    }
}
